package com.imooc.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author liuhuan
 * @date 2018/7/28 10:16
 * @description
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {
    private Session session;

    private static CopyOnWriteArraySet<WebSocket> webSocketSet=new CopyOnWriteArraySet<>();

    /**
     * 建立连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        this.session=session;
        webSocketSet.add(this);
        log.info("【websocket信息】有新的连接，总数={}",webSocketSet.size());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.info("【websocket信息】连接断开，总数={}",webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message){
        log.info("【websocket信息】收到客户端的消息:{}",message);

    }

    public void sendMessange(String message){
        for(WebSocket webSocket:webSocketSet){
            log.info("【websocket信息】广播信息:{}",message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                log.error("【websocket信息】发送信息失败",e);
            }
        }
    }
}
